<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="">
        <el-breadcrumb-item
          ><div class="div1">基本配置</div></el-breadcrumb-item
        >
        <el-breadcrumb-item
          ><div class="div2">角色管理</div></el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <!-- 面包屑导航 teamManage -->

    <div class="content">
      <h3>角色</h3>
      <h4>数据筛选</h4>
      <div>
        <el-form
          :inline="true"
          :model="roleForm"
          :rules="roleRules"
          ref="roleForm"
          label-width="50px"
        >
          <el-form-item label="角色">
            <el-input v-model="roleForm.name" size="mini"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="mini"
              plain
              @click="submitForm('roleForm')"
              >查询</el-button
            >
            <el-button
              type="primary"
              size="mini"
              plain
              @click="resetForm('roleForm')"
              >重置</el-button
            ></el-form-item
          >
        </el-form>
      </div>
    </div>
    <div class="content">
      <h3>角色列表</h3>
      <lb-table
        :column="column"
        :data="roleList"
        pagination
        :total="page.totalNum"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 20, 30, 50]"
        :current-page.sync="page.currentPage"
        :page-size="page.pageSize"
        @size-change="handleSizeChange"
        @p-current-change="handleCurrentChange"
      >
      </lb-table>
    </div>
    <!-- 管理客户等级 -->

    <!-- ============================= el-dialog ============================= -->

    <el-dialog
      title="关联权限组"
      :visible.sync="dialog.visible"
      width="625px"
      :append-to-body="true"
      :before-close="handleClose"
      :filterable="true"
    >
      <div class="dialog-content">
        <el-transfer
          v-model="permissionSelected"
          :data="permissionAllList"
          :titles="['未选择', '已选择']"
        ></el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="dialogConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from "element-ui";
import LbTable from '../../../components/lb-table/lb-table'
export default {
  name: 'role',
  components: {
    LbTable
  },
  data () {
    return {
      permissionAllList: [],
      permissionSelected: [],
      column: [{
        label: '角色',
        prop: 'name'
      }, {
        label: '权限组',
        prop: 'authListStr'
      },
      {
        label: '最后更新时间',
        prop: 'updatedTime'
      },
      {
        label: '操作',
        render: (h, scope) => {
          return (
            <div>
              <el-link
                size="mini"
                type="primary"
                onClick={() => { this.showDialog(scope.$index, scope.row) }}>查看 / 绑定</el-link>
            </div>
          )
        }
      }],
      roleForm: {
        name: ''
      },
      roleRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
      },
      page: {
        pageNo: 1,
        pageSize: 10,
        totalNum: 0,
        currentPage: 1,
      },
      roleList: [],
      dialog: {
        visible: false,
        title: ''
      },
      currentRow: {},
      parArray: [] // 按钮权限
    };
  },
  created () {
    this.getButtonTreeDto() // 获取权限设定
    this.fetchData()
  },
  methods: {
    getButtonTreeDto () {
      // 获取权限设定
      this.limits = JSON.parse(sessionStorage.getItem('limit'))
      const params = this.limits.buttonTreeDto.filter(
        (item) => item.menuCode === 'roleCode'
      )
      params[0].buttonList.forEach((item) => {
        this.parArray.push(item.code)
      })
      console.log(this.parArray)
    },
    fetchData (type) {
      if (type == 'search') { this.page.pageNo = 1 }
      const params = {
        id: sessionStorage.getItem("user_id"),
        name: this.roleForm.name,
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize
      }
      this.$api.rolePageList(params).then((res) => {
        res.data.list.map((e) => {
          let str = ''
          e.authList.forEach(e => {
            str += `${e.name}、`
          });
          e.authListStr = str.substring(0, str.length - 1)
          if (e.authList.length == 0) { e.authListStr = '-' }
        })
        this.roleList = res.data.list
        this.page.totalNum = res.data.totalNum
        if (res.data.list.length === 0) { Message.warning('没有搜索出相关内容'); }
      }).catch((err) => {
        console.log(err)
      })
    },
    handleCurrentChange (currentChange) {
      this.page.pageNo = currentChange
      this.fetchData()
    },
    handleSizeChange (sizeChange) {
      this.page.pageSize = sizeChange
      this.fetchData()
    },
    // 显示  dialog
    showDialog (index, row) {
      // console.log(index, row)
      this.currentRow = row
      this.dialog.visible = true
      this.getPermissionAllList(row)
      this.setPermissionSelected(row)
    },
    // 权限组列表查询
    getPermissionAllList (row) {
      if (this.permissionAllList.length === 0) {
        this.$api.permissionAllList().then((res) => {
          res.data.forEach((e) => {
            e.key = e.id
            e.label = e.name
          })
          this.permissionAllList = res.data
          this.setPermissionSelected(row)
        }).catch((err) => {
          console.log(err)
        })
      }
    },
    setPermissionSelected (row) {
      let arr = []
      this.permissionAllList.forEach((e) => {
        row.authList.forEach((ee) => {
          if (e.name == ee.name) { arr.push(e.id) }
        })
      })
      this.permissionSelected = arr
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    dialogConfirm () {
      this.$confirm('是否确认修改权限？')
        .then(_ => {
          this.dialog.visible = false
          this.setRoleUpdateAuth()
        })
        .catch(_ => { });
    },
    // 修改角色绑定权限组
    setRoleUpdateAuth (row) {
      if (this.parArray.indexOf("rolefp") == -1) { return this.$message({ type: 'warning', message: '权限不足!' }); }
      let data = {
        roleId: this.currentRow.id,
        authList: this.permissionSelected
      }
      this.$api.roleUpdateAuth(data).then((res) => {
        this.fetchData()
        this.$message.success("操作成功！");
        console.log(res)
      }).catch((err) => {
        console.log(err)
      })
    },
    // 搜索 表单验证
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.fetchData('search')
          // this.dialog.visible = false;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 重置搜索
    resetForm (formName) {
      this.$refs[formName].resetFields();
      this.roleForm.name = ''
      this.page.pageNo = 1
      this.page.pageSize = 10
      this.totalNum = 0
      this.page.currentPage = 1
      this.fetchData()
    },

  }
}
</script>

<style scoped lang="scss">
.div1 {
  margin-left: -16px;
  background: url(../../../assets/breadcrumb2.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}
.div2 {
  margin-left: -16px;
  background: url(../../../assets/breadcrumb1.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #fff;
}
.div3 {
  margin-left: -8px;
  background: url(../../../assets/breadcrumb3.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}
.content {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #ffffff;
  h3 {
    position: relative;
    margin-bottom: 20px;
    padding-left: 10px;
    &:before {
      position: absolute;
      top: 5px;
      left: 0;
      display: inline-block;
      content: "";
      width: 3px;
      height: 20px;
      background-color: #2d7edf;
    }
  }
  h4 {
    padding-top: 10px;
    border-top: 1px solid #bbbbbb;
  }
}
</style>
